# 实现一个自己的动态数组
class MyArrayList():
    INIT_CAPACITY = 10
    def __init__(self,capacity=INIT_CAPACITY):
        self.capacity = capacity
        self.data = [None] * capacity
        self.size = 0

    # 增
    def add(self,e,index):
        self._check_position_index(index)
        for i in range(self.size-1 ,index -1, -1):
            self.data[i+1] = self.data[i]
        self.data[index] = e
        self.size += 1
        if self.size == self.capacity:
            self._resize(self.capacity *2)
    def add_first(self,e):
        self.add(e,0)
    def append(self,e):
        self.add(e,self.size)
    # 删
    def remove(self,index):
        self._check_element_index(index)
        for i in range(index+1,self.size):
            self.data[i-1] = self.data[i]
        self.data[self.size-1] = None
        self.size -= 1
        if self.size <= self.capacity/4:
            self._resize(self.capacity *0.5)
    # 改
    def set(self,e,index):
        self._check_element_index(index)
        self.data[index] = e
    # 查
    def get(self,index):
        self._check_element_index(index)
        return self.data[index]
    # 扩容或者缩容方法
    def _resize(self,new_capacity):
        new_data = [None] * int(new_capacity)
        for index in range(self.size):
            new_data[index] = self.data[index]
        self.data = new_data
        self.capacity = new_capacity
        # size不用变在 增删函数里维护

    #工具方法
    def __len__(self):
        return self.size
    def __str__(self):
        return str(self.data)

    def _is_element_index(self,index):
        return 0 <= index <self.size

    def _is_position_index(self,index):
        return 0 <= index <=self.size

    def _check_element_index(self,index):
        if not self._is_element_index(index):
            raise IndexError(f"Index: {index}, Size: {self.size}")

    def _check_position_index(self,index):
        if not self._is_position_index(index):
            raise IndexError(f"Index: {index}, Size: {self.size}")


if __name__ == '__main__':
    a = MyArrayList()
    for i in range(10):
        a.append(i)
    a.add_first(100)
    a.add(20,1)
    a.remove(1)
    a.remove(1)
    a.remove(1)
    a.remove(1)
    a.remove(1)
    a.remove(1)
    a.remove(1)

    print(a.__str__())